package com.wswy.wzcx.ui.main.home;

import android.content.Context;
import android.support.annotation.Nullable;
import com.blankj.utilcode.util.SPUtils;
import com.che.libcommon.api.ApiOptionalResultObserver;
import com.che.libcommon.api.BaseResult;
import com.che.libcommon.api.page.PageList;
import com.che.libcommon.api.page.Pagination;
import com.che.libcommon.utils.optional.Optional;
import com.wswy.wzcx.api.Api;
import com.wswy.wzcx.model.news.NewsModel;
import io.reactivex.Single;
import io.reactivex.functions.IntFunction;
import java.util.Calendar;
import java.util.List;

class HomeNewsPresenter{

  private static final String TAG = "HomeNewsPresenter";

  private INewsView mView;

  private String type;


  private Pagination<NewsModel> newsPagination;

  private HomeNewsLoader adLoader=null;


  HomeNewsPresenter(Context context,INewsView view,String type){
    mView = view;
    this.type = type;


    adLoader = new HomeNewsLoader(context);

  }

  private boolean needLoadMyNews(){
    long show = SPUtils.getInstance().getLong("lsat_ad_show",0);
    if(show < 1000){
      return true;
    }

    Calendar calendar = Calendar.getInstance();
    int y = calendar.get(Calendar.YEAR);
    int m = calendar.get(Calendar.MONTH);
    int d = calendar.get(Calendar.DAY_OF_MONTH);

    calendar.setTimeInMillis(show);

    int lastY = calendar.get(Calendar.YEAR);
    int lastM = calendar.get(Calendar.MONTH);
    int lastD = calendar.get(Calendar.DAY_OF_MONTH);

    return y != lastY || m != lastM || d != lastD;
  }





  Object loadNews() {



    newsPagination = new Pagination<NewsModel>(new IntFunction<Single<Optional<PageList<NewsModel>>>>() {
      @Override
      public Single<Optional<PageList<NewsModel>>> apply(int i) throws Exception {
        return Api.get().getNews(i,type);
      }
    });

    newsPagination.setCallback(new ApiOptionalResultObserver<List<NewsModel>>() {
      @Override
      protected void onApiResult(@Nullable List<NewsModel> list) {
        if (newsPagination.isFirst()){
          mView.showNews(list);
        }else {
          mView.showAddNews(list);
        }
      }

      @Override
      protected void onApiError(@Nullable BaseResult result) {

      }
    });

    newsPagination.preLoad();

    //adLoader.load();

    return newsPagination;
  }


  Object reload(){
    if (newsPagination != null){
      newsPagination.release();
    }

    return loadNews();

  }


  private void showData(){

  }

}
